const websocket = require("ws");

const websocketServer = new websocket.Server({
  // 创建一个端口为8000的websocket服务器
  port: 8000,
});

let clients = {};
let clientNum = 0;
ws.on("connection", (client) => {
  //监听，连接客户端
  //给每个连接的的客户端创建一个名字
  client.name = ++clientNum;
  clients[client.name] = client; //'1':client

  //用client实例监听自己发送的四个常用事件:open,message,close,error
  client.on("message", (msg) => {
    //监听客户端发送的message事件，接收客户端发送的消息
    console.log("用户" + client.name + "说:" + msg);
    broadcast(client, msg);
  });
  //监听报错事件
  client.on("error", (err) => {
    //监听客户端错误事件
    if (err) {
      console.log(err);
    }
  });
  //监听关闭事件(下线)
  client.on("close", () => {
    broadcastQuit(client);
    console.log("用户" + client.name + "下线了");
    delete clients[client.name]; //从容器中删除下线的客户端实例
  });
});
//广播方法
function broadcast(client, msg) {
  //对所有客户端进行广播
  for (let key in clients) {
    clients[key].send("用户" + client.name + "说:" + msg);
  }
}

//广播下线
function broadcastQuit(client) {
  for (let key in clients) {
    clients[key].send("系统提示:用户" + client.name + "下线了");
  }
}
